package com.aliyun.messagemgt.application.service.excel;

import com.aliyun.messagemgt.application.service.MessageTemplateService;
import com.aliyun.messagemgt.common.exceptions.BaseException;
import com.aliyun.messagemgt.common.dto.response.ResultMap;
import com.aliyun.messagemgt.dto.MessageTemplate;
import com.aliyun.messagemgt.dto.excel.BaseMessageSourceExcel;
import com.aliyun.messagemgt.dto.excel.MessageTemplateExcel;
import com.aliyun.messagemgt.repository.mappers.ExcelExcutorMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ImportExcelServiceImpl implements ImportExcelService {

    @Autowired
    private MessageTemplateService messageTemplateService;

    @Autowired
    private ExcelExcutorMapper excelExcutorMapper;

    /**
     * 外循环插入，效率较低，可优化成mybatis批量插入
     *
     * @param list
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResultMap importMessageTemplateExcel(List<MessageTemplateExcel> list) {
        ResultMap  resultMap = new ResultMap<>();
        for (MessageTemplateExcel excelparam : list) {
            MessageTemplate messageTemplateParam = new MessageTemplate();
            BeanUtils.copyProperties(excelparam, messageTemplateParam);
            try {
                messageTemplateService.checkTemplate(messageTemplateParam);
            }catch (BaseException e){
                resultMap.setErrCode(1);
                resultMap.setErrMsg(messageTemplateParam.getTemplateName()+"  该消息模板存在重复，请重新填写：" + e.getMessage()
                );
                return  resultMap;
            }
            messageTemplateService.saveTemplate(messageTemplateParam);
        }
        return  resultMap;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResultMap importBaseMessageSourceExcel(List<BaseMessageSourceExcel> list) {
        ResultMap  resultMap = new ResultMap<>();
        resultMap.setErrCode(0);
        resultMap.setErrMsg("excel数据导入成功");
        try {
            excelExcutorMapper.importBaseMessageSourceExcel(list);
        }catch (Exception e){
            resultMap.setErrCode(1);
            resultMap.setErrMsg("检查excel是否存在重复的场景编码");
        }
        return resultMap;
    }
}
